package org.dxy.domain.handler.product;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IProductRepository;
import org.dxy.domain.command.product.UnassignProductRouteCommand;
import org.dxy.domain.event.DomainEvent;
import org.dxy.domain.model.aggregate.Product;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 解绑产品工艺路线命令处理器
 * @author: dxy
 * @createTime: 2025/8/17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UnassignProductRouteCommandHandler implements CommandHandler<UnassignProductRouteCommand, Void> {

    private final IProductRepository productRepository;

    @Transactional
    @Override
    public CommandResult<Void> handle(UnassignProductRouteCommand command) {
        try {
            log.info("开始处理解绑产品工艺路线命令: productId={}, routeId={}", 
                    command.productId(), command.routeId());

            Product product = productRepository.findById(command.productId());
            if (product == null) {
                return CommandResult.fail("产品不存在");
            }

            product.unassignRoute(command);
            productRepository.save(product);

            List<DomainEvent> events = product.getDomainEvents();
            for (DomainEvent event : events) {
                log.debug("发布领域事件: {}", event);
            }

            log.info("解绑产品工艺路线命令处理完成: productId={}, routeId={}", 
                    command.productId(), command.routeId());
            return CommandResult.success(null, "产品工艺路线解绑成功");

        } catch (IllegalArgumentException | IllegalStateException e) {
            log.warn("解绑产品工艺路线失败，业务规则校验不通过: productId={}, error={}", 
                    command.productId(), e.getMessage());
            return CommandResult.fail(e.getMessage());
        } catch (Exception e) {
            log.error("解绑产品工艺路线失败: productId={}", command.productId(), e);
            return CommandResult.fail("解绑产品工艺路线失败: " + e.getMessage());
        }
    }
}